const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

// YYYYMMDDHHMMSS
const formatNumberTime = date => {

  // 提取年份、月份和日期
  let year = date.getFullYear(); // 年份
  let month = date.getMonth() + 1; // 月份，注意JavaScript的月份是从0开始的，所以需要加1
  let day = date.getDate(); // 日期

  let hour = date.getHours()
  let minute = date.getMinutes()
  let second = date.getSeconds()
  // 格式化为两位数
  let formattedYear = year.toString()//.slice(-2); // 年份取后两位
  let formattedMonth = (month < 10 ? '0' + month : month); // 月份如果不是两位数，前面补0
  let formattedDay = (day < 10 ? '0' + day : day); // 日期如果不是两位数，前面补0

  let formattedHour = (hour < 10 ? '0' + hour : hour); // 小时如果不是两位数，前面补0
  let formattedMinute = (minute < 10 ? '0' + minute : minute); // 分钟如果不是两位数，前面补0
  let formattedSecond = (second < 10 ? '0' + second : second); // 秒数如果不是两位数，前面补0
  // 拼接成"YYMMDD"格式的字符串
  let result = formattedYear + formattedMonth + formattedDay + formattedHour + formattedMinute + formattedSecond;
  console.log(result); 
  return result
}

// 小时分钟秒 HHMMSS
const formatHHMMSSTime = date => {
  let hour = date.getHours()
  let minute = date.getMinutes()
  let second = date.getSeconds()
  // 格式化为两位数
  let formattedHour = (hour < 10 ? '0' + hour : hour); // 小时如果不是两位数，前面补0
  let formattedMinute = (minute < 10 ? '0' + minute : minute); // 分钟如果不是两位数，前面补0
  let formattedSecond = (second < 10 ? '0' + second : second); // 秒数如果不是两位数，前面补0
  // 拼接成"YYMMDD"格式的字符串
  let result = formattedHour + formattedMinute + formattedSecond;
  console.log(result); 
  return result
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 写一个获得openid的办法

function getopenid() {
  let that = this
  var openid = ""
  try {
    openid = wx.getStorageSync("openid")

    if (openid) {
      // Do something with return value
      if (openid != "") {
        this.globalData.openid = openid
      }
    }
  } catch (e) {
    // Do something when catch error
  }

  if (openid == "") {

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log("util.js -> getopenid -> wx.login -> res.code =" + res.code)
        // 服务器建立一个专门登录的算法。
        // 服务器的 wxjscode2sessionpost 在 https://api.weixin.qq.com/sns/jscode2session?appid=wxf130e68214a5c958&secret=d57e7eab6271fce883668caf57772837&js_code=JSCODE&grant_type=authorization_code
        // wxf130e68214a5c958
        // d57e7eab6271fce883668caf57772837
        // 061zt60004vF3M1oTU200V2HNZ1zt60Q
        wx.request({
          url: 'https://xuanfangyi.com/wxjscode2sessionpost/',

          method: 'post',
          data: {
            code: res.code
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success(res) {
            // {"status":"OK","session_key":"cFc44uZGiTRNURk1BKkZgg==","openid":"oN2Ka5IRj8mOxoGra1o5LQOs9ho0"}
            console.log(res.data)
            wx.setStorage({
              key: "openid",
              data: res.data.openid
            })
            openid = res.data.openid
            //that.globalData.openid = openid

          }, // success (res) {
          fail(res) {
            wx.showToast({
              title: "网络登录失败",
              icon: 'error',
              duration: 2000
            })
          }
        }) // wx.request({
      }
    })

  } // if (openid == "") {
    
} // end of getopenid 写一个获得openid的办法

// 小程序js有sleep函数吗?怎么用啊 https://developers.weixin.qq.com/community/develop/doc/0000a6affd0dd8bb1908347f75b000
// 该方法好像不太管用。
function wsndelay(milSec) {
  return new Promise(resolve => {
    setTimeout(resolve, milSec)
  });
}

// js中自定义方法实现停留几秒sleep https://www.jb51.net/article/52105.htm
function wsnsleep(numberMillis) { 
  var now = new Date(); 
  var exitTime = now.getTime() + numberMillis; 
  while (true) { 
  now = new Date(); 
  if (now.getTime() > exitTime) 
  return; 
  } 
}

/**
 * 将小程序的API封装成支持Promise的API
 * @params fn {Function} 小程序原始API，如wx.login
 */
const wxPromisify = fn => {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        resolve(res)
      }

      obj.fail = function (res) {
        reject(res)
      }

      fn(obj)
    })
  }
}

module.exports = {
  formatTime: formatTime,
  formatHHMMSSTime: formatHHMMSSTime,
  getopenid: getopenid,
  formatNumberTime: formatNumberTime,
  wsndelay: wsndelay,
  wsnsleep: wsnsleep,
  wxPromisify: wxPromisify
}